package com.nageoffer.jobtrain.projects.common.biz.user;

import cn.hutool.core.util.StrUtil;
import com.nageoffer.jobtrain.common.toolkit.biz.user.UserInfoDTO;
import com.nageoffer.jobtrain.common.toolkit.constant.JWTPlayLoadConstant;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 用户身份信息过滤器
 * author：唐晨
 */
@Slf4j
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String id = request.getHeader(JWTPlayLoadConstant.LOGIN_PLAY_LOAD_ID);
        String username = request.getHeader(JWTPlayLoadConstant.LOGIN_PLAY_LOAD_USERNAME);
        // 从请求报头中获取用户信息设置到用户上下文中
        if (StrUtil.isNotBlank(id) && StrUtil.isNotBlank(username)) {
            UserInfoDTO userInfo = UserInfoDTO.builder()
                    .id(id)
                    .username(username)
                    .build();
            UserContext.setUser(userInfo);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
}
